<?php
require_once 'init_app.php';

set_time_limit(0); 
ob_start();

$shop = ORM::factory('shop', 26);
$shop->set_as_current();
$category_id = 3; 

$count_found = $count_market = 0;
$products = ORM::factory('product')->get_products($category_id, 0); 
$count = 0;
foreach ($products as $product) {
    $count++;
    
    if ($count > 10) {
        break;
    }
    echo $count.' - '.$product->name . " ----- " . $product->get_clean_name();
    ob_flush();
    flush();
    
    $model = ORM::factory('model')->find_models($product->name);
    if ($model && ($product->get_clean_name() == $model->get_clean_name())) {
        //$product->to_model($model);
        $count_found++;
        echo '<span style="color:red;">В '.$model->name.'</span><br />';
        continue;        
    }
    
    sleep(mt_rand(5, 10));   // Не ддосим Маркет 
    // Нашей модели не нашлось, пробуем искать в Маркете
    $market_url = Model_ReviewParser_YandexMarket::instance()->get_reviews_url($product->clean_name);
    $model_name = null;
    if ($market_url) {
        sleep(mt_rand(1, 3));
        $model_name = Model_ReviewParser_YandexMarket::instance()->get_model_name($market_url);
        echo '<span style="color:green;">Пробуем '.$model_name.' - '.$market_url.'</span>';
        if ($model_name && ($product->get_clean_name() == Model_Main::get_clean_name($model_name))) {
            // Создаем модель
            //$model = ORM::factory('model')->add_model($model_name, $market_url);
            //$product->to_model($model); 
            $count_market++;
            echo ' -- <span style="color:green;">В '.$model_name.'</span><br />';
            continue;  
        }
    }  
    echo '<br />';
}
echo '<br /><br />Всего - '.count($products).'<br />'.
    'Нашлось наших моделей - '.$count_found.'<br />'.
    'Добавили из Маркета - '.$count_market.'<br />';